package com.cn.data.thread.countdownlatch;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: chenl
 * @Date: 2019/3/2 23:07
 *
 * CyclicBarrier和CountDownLatch的区别
CountDownLatch的计数器只能使用一次，而CyclicBarrier的计数器可以使用reset()方法重置，可以使用多次，所以CyclicBarrier能够处理更为复杂的场景；

CyclicBarrier还提供了一些其他有用的方法，比如getNumberWaiting()方法可以获得CyclicBarrier阻塞的线程数量，isBroken()方法用来了解阻塞的线程是否被中断；

CountDownLatch允许一个或多个线程等待一组事件的产生，而CyclicBarrier用于等待其他线程运行到栅栏位置。
 */
public abstract class BaseHealthChecker implements Runnable {

    private CountDownLatch countDownLatch;

    private String serviceName;

    private Boolean serviceUp;

    public BaseHealthChecker(CountDownLatch countDownLatch, String serviceName) {
        super();
        this.countDownLatch = countDownLatch;
        this.serviceName = serviceName;
        this.serviceUp = false;
    }

    @Override
    public void run() {
        try {
            verifyService();
            serviceUp = true;
        } catch (Throwable t) {
            t.printStackTrace(System.err);
            serviceUp = false;
        } finally {
            if (countDownLatch != null) {
                countDownLatch.countDown();
            }
        }
    }


    public Boolean isSericeUp() {
        return serviceUp;
    }

    public String getServiceName() {
        return serviceName;
    }

    /**
     * 校验服务是否起来
     */
    public abstract void verifyService();
}